import React, { useEffect, useState } from "react";
import { isPromise } from "@ct0/functions";
import Radio from "../../../Radio";
import type { FieldBaseType } from "../../type";
import type { RadioOption } from "../../../Radio/type";

export default function RadioField({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<string | number>;
  isValid: boolean;
  onChange: (value: string | number) => void;
}) {
  const { value, defaultValue, disabled, options } = field;
  const [opts, setOpts] = useState<Array<RadioOption<string | number>>>([]);

  useEffect(() => {
    if (typeof options == "undefined") return;
    else if (typeof options == "function") {
      const opt = options();
      if (isPromise(opt)) opt.then((r) => setOpts(r));
      else setOpts(opt as any);
    } else {
      setOpts(options);
    }
  }, [options]);

  return (
    <Radio
      value={value ?? defaultValue}
      className={isValid ? undefined : "radio-invalid"}
      onChange={onChange}
      border
      disabled={disabled}
      options={opts}
    />
  );
}
